package com.pubinfo.passbook.common.utils.bank;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

@Slf4j
public class BankAesUtil {
  
  private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  
  private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
  
  private static final String ALGORITHM = "AES";
  
  /**
   * 参数加密
   *
   * @param encryptKey
   * @param content
   * @return
   */
  public static String encrypt(String encryptKey, String content) {
    try {
      SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey.getBytes(), ALGORITHM);
      Cipher ecipher = Cipher.getInstance(TRANSFORMATION);
      ecipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
      return Base64Utils.encodeToString(ecipher.doFinal(content.getBytes(DEFAULT_CHARSET)));
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }
  
  /**
   * 参数解密
   *
   * @param encryptKey
   * @param content
   * @return
   */
  public static String decrypt(String encryptKey, String content) {
    try {
      SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey.getBytes(), ALGORITHM);
      Cipher dcipher = Cipher.getInstance(TRANSFORMATION);
      dcipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
      return new String(dcipher.doFinal(Base64Utils.decodeFromString(content)),
          DEFAULT_CHARSET);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }
  
}
